package com.own.business.log.login.persistence.business.hook;

import com.alibaba.fastjson2.JSON;
import com.own.business.log.login.persistence.business.service.LogLoginElasticService;
import com.own.business.log.login.persistence.entity.po.LogLoginElasticPo;
import com.own.component.log.login.core.BaseLastLoginTimeMethod;
import com.own.component.log.login.core.PersistenceLogLoginHook;
import com.own.component.log.login.em.LogLoginStatusEnum;
import com.own.component.log.login.entity.LogLoginEntity;
import com.own.component.util.time.ZonedDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * DefaultAfterLogLoginHook
 *
 * @author chenxueli
 * @date 2023-12-20 10:28:56
 */
@Slf4j
@Component
public class DefaultAfterLogLoginHook implements PersistenceLogLoginHook, BaseLastLoginTimeMethod {

    @Resource
    private LogLoginElasticService logLoginElasticService;

    /**
     * 执行方法
     *
     * @param entity 日志信息
     */
    @Override
    public void run(LogLoginEntity entity) {
        var po = new LogLoginElasticPo();
        var loginUser = entity.getLoginUser();
        if (loginUser != null) {
            po.setFkUserId(loginUser.userId());
            po.setUserName(loginUser.userName());
            po.setToken(loginUser.token());
        }
        po.setGmtCreate(ZonedDateTimeUtil.of(entity.getLoginTime()));
        po.setIp(entity.getIp());
        po.setClient(entity.getClient());
        po.setStatus(entity.getStatus().getType());
        po.setLoginAccount(entity.getLoginAccount());
        po.setLoginType(entity.getLoginType());
        po.setLoginCode(entity.getLoginCode());
        po.setExtra(JSON.toJSONString(entity.getExtra()));
        po.setTraceId(entity.getTraceId());
        logLoginElasticService.add(po);
    }

    /**
     * 根据用户id查询最后一次成功的登录日志信息
     *
     * @param userId 用户id
     * @return 最后一次成功的登录日志信息
     */
    @Override
    public LogLoginEntity lastLoginTime(Long userId) {
        var logLogin = logLoginElasticService.getLastLoginTimeByUserId(userId);
        // 转成entity
        if (logLogin != null) {
            return LogLoginEntity.builder()
                    .status(LogLoginStatusEnum.SUCCESS)
                    .loginAccount(logLogin.getLoginAccount())
                    .loginType(logLogin.getLoginType())
                    .loginCode(logLogin.getLoginCode())
                    .ip(logLogin.getIp())
                    .client(logLogin.getClient())
                    .loginTime(logLogin.getGmtCreate())
                    .build();
        }
        return LogLoginEntity.NONE;
    }

}
